package com.zbw.printlibrary.printSub;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.lkl.cloudpos.aidl.AidlDeviceService;
import com.lkl.cloudpos.aidl.casher.AidlCashbox;
import com.lkl.cloudpos.aidl.casher.AidlCasher;
import com.lkl.cloudpos.aidl.printer.AidlPrinter;
import com.lkl.cloudpos.aidl.printer.AidlPrinterListener;
import com.lkl.cloudpos.aidl.printer.PrintItemObj;
import com.zbw.printlibrary.bean.AttributeBean;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.PrinterControlCommon;
import com.zbw.printlibrary.util.PrintThreadPoolManager;
import com.zbw.printlibrary.util.SerialPort;
import com.zbw.printlibrary.util.SerialPortFinder;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import xprinter.xpos.printservice.IXposService;

import static com.zbw.printlibrary.util.PrintTextUtil.createExplicitFromImplicitIntent;

/**
 * Created by cyj on 2019-07-25.
 * 拉卡拉设备打印
 */

public class PrintLKL extends PrinterControlCommon {
    public IXposService xposService = null;
    private Context mContext;
    private IPrintCallBack mCallBack;
    private AidlPrinter printerDev = null;
    private  AidlDeviceService serviceManager;
    public static final String LKL_SERVICE_ACTION = "lkl_cloudpos_device_service";
    public  static final String LAL_PACKAGE="com.landicorp.android.lakala";
    public PrintLKL(@NonNull Context context, IPrintCallBack callback) {
        mContext = context;
        this.mCallBack = callback;
    }

    @Override
    public void connectPrinter() {
        if (xposService == null) {
            try {
                Intent intent =new Intent();
                 intent.setPackage(LAL_PACKAGE);
                intent.setAction(LKL_SERVICE_ACTION);
                Intent eintent = new Intent(createExplicitFromImplicitIntent(mContext,intent));
                mContext.bindService(eintent, connService, Context.BIND_AUTO_CREATE);
            }catch (Exception e){
                Toast.makeText(mContext, "没有找到拉卡拉模块", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
            // boolean flag=  mContext.bindService(intent, connService, Context.BIND_AUTO_CREATE);
        }
    }

    @Override
    public void disConnectPrinter() {
        try {
            Intent intent = new Intent();
             intent.setPackage(LAL_PACKAGE);
            intent.setAction(LKL_SERVICE_ACTION);
            Intent eintent = new Intent(createExplicitFromImplicitIntent(mContext,intent));
            mContext.getApplicationContext().stopService(eintent);
//            mContext.unbindService(connService);
            if (xposService != null) {
                mContext.getApplicationContext().unbindService(connService);
                xposService = null;
            }
            mCallBack.onDisConnect("断开成功",true);
            if (mContext != null) {
                mContext = null;
            }

        }catch (Exception e){
            e.printStackTrace();
            mCallBack.onDisConnect("断开失败",false);
        }

    }

    @Override
    public void printTest(final List<String> list) {
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    if (printerDev!=null) {
                        printerDev.printText(new ArrayList<PrintItemObj>(){
                            {
                                try{
                                    add(new PrintItemObj(list.get(0),24,true, PrintItemObj.ALIGN.CENTER));
                                    add(new PrintItemObj(list.get(1),8,true, PrintItemObj.ALIGN.CENTER));
                                    for(int i=2;i<list.size();i++){
                                        add(new PrintItemObj(list.get(i)));
                                    }
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                            }

                        }, new AidlPrinterListener.Stub() {

                            @Override
                            public void onPrintFinish() throws RemoteException {
                                autoCutPaper();
                                mCallBack.onPrintResult(true);

                            }

                            @Override
                            public void onError(int arg0) throws RemoteException {
                                Log.i("tag", "onRunResult:" + arg0);
                                mCallBack.onPrintResult(false);
                            }
                        });
                    }else{
                        mCallBack.onPrintResult(false);
                    }

                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    mCallBack.onPrintResult(false);
                    e.printStackTrace();
                }

            }});
    }

    @Override
    public void printString(final List<AttributeBean> testList) {
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    if (printerDev!=null) {
                        printerDev.printText(new ArrayList<PrintItemObj>(){
                            {
                                try{
                                    for(int i=0;i<testList.size();i++){
                                        int fontSize=0;
                                        boolean isBold=false;
                                        PrintItemObj.ALIGN align = PrintItemObj.ALIGN.LEFT;
                                        switch (testList.get(i).getFont_size()){
                                            case 0:
                                                fontSize=8;
                                                isBold=false;
                                                break;
                                            case 1:
                                                fontSize=16;
                                                isBold=true;
                                                break;
                                            case 2:
                                                fontSize=24;
                                                isBold=true;
                                                break;
                                        }

                                        switch (testList.get(i).getFont_gray()){
                                            case 0:
                                                align=PrintItemObj.ALIGN.LEFT;
                                                break;
                                            case 1:
                                                align=PrintItemObj.ALIGN.CENTER;
                                                break;
                                            case 2:
                                                align=PrintItemObj.ALIGN.RIGHT;
                                                break;
                                        }

                                        add(new PrintItemObj(testList.get(i).getContext(),fontSize,isBold,align));
                                    }
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                            }

                        }, new AidlPrinterListener.Stub() {

                            @Override
                            public void onPrintFinish() throws RemoteException {
                                autoCutPaper();
                                mCallBack.onPrintResult(true);

                            }

                            @Override
                            public void onError(int arg0) throws RemoteException {
                                Log.i("tag", "onRunResult:" + arg0);
                                mCallBack.onPrintResult(false);
                            }
                        });
                    }else{
                        mCallBack.onPrintResult(false);
                    }

                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    mCallBack.onPrintResult(false);
                    e.printStackTrace();
                }

            }});
    }

    @Override
    public void printStringAndBitmap(List<String> testList, LinkedHashMap<Integer,Bitmap> bitmapHashMap) {
        printTest(testList);
    }

    @Override
    public void blueConnect(String address) {

    }

    @Override
    public void disBlueConnect() {

    }


    @Override
    public void openMoneyBox() {
        casherBox();
    }

    @Override
    public boolean isConnected() {
        if (xposService == null) {
            return false;
        }else{
            return true;
        }
    }

    /**
     * 开钱箱,拉卡拉
     */
    public void casherBox(){
        if (true) {
            //开钱箱1
            try {
                AidlCasher cash = AidlCasher.Stub.asInterface(serviceManager.getCasher());
                AidlCashbox cashBox = AidlCashbox.Stub.asInterface(cash.getCashbox());
                if (cashBox != null) cashBox.open();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Toast.makeText(mContext, "没有找到拉卡拉模块", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }else{
            //开钱箱2
            SerialPortFinder finder = new SerialPortFinder();
            //找到USB钱箱串口
            List<String> drivers = finder.getAllUsbDevicesPath();
            for (String driver:drivers) {
                try {
                    SerialPort serialPort = new SerialPort(new File(driver), 9600, 0);
                    OutputStream outputStream = serialPort.getOutputStream();
                    //发送20约字节的长度就可以
                    outputStream.write("1234567890123456789012345".getBytes());
                    outputStream.flush();
                    outputStream.close();
                    serialPort.close();
                    serialPort = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 切纸
     */
    public void autoCutPaper(){
        try {
            AidlCasher cash = AidlCasher.Stub.asInterface(serviceManager.getCasher());
            cash.autoCutPaper();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Toast.makeText(mContext,"没有找到拉卡拉模块",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    //设别服务连接�?
    private ServiceConnection connService = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName name, IBinder serviceBinder) {
            if(serviceBinder != null){	//绑定成功
                serviceManager = AidlDeviceService.Stub.asInterface(serviceBinder);
                try {
                    printerDev = AidlPrinter.Stub.asInterface(serviceManager.getPrinter());
                    mCallBack.onConnect("连接成功",true);
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            printerDev = null;
            mCallBack.onDisConnect("断开成功",true);

        }
    };

    @Override
    public void printString(List<AttributeBean> testList, int width) {

    }

}
